package dot;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.jgrapht.Graph;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.SimpleGraph;

import cover.vertex.Vertex;

public class Import {

	/**
	 * Converting specified file.dot to org.jgrapht.Graph </br> </br><font
	 * color="red">WARNING!!!</font> there is couple of restrics for .dot
	 * file:</br></br> 1) EVERY node/edge on NEW string </br>2) NO special
	 * attributes</br> 3) Each string MUST be productive</br></br>
	 * 
	 * @param pathToFile
	 * @return
	 * @throws IOException
	 */
	public Graph<Vertex, DefaultEdge> genGraphFromDot(String pathToFile)
			throws IOException {

		if (!pathToFile.endsWith(".dot")) {
			System.out.println("Cannot recognize " + pathToFile
					+ " as .dot formatted file");
			throw new IOException();
		}

		Graph<Vertex, DefaultEdge> graph = new SimpleGraph<Vertex, DefaultEdge>(
				DefaultEdge.class);
		List<Vertex> list = new ArrayList<Vertex>();
		
		BufferedReader in = new BufferedReader(new FileReader(pathToFile));
		String str = in.readLine();
		while ((str = in.readLine()) != null) {
			if (str.contains("--")) {
				String id1 = str.substring(0, str.indexOf("-"));
				id1 = id1.replaceAll(" ", "");
					String id2 = str.substring(str.indexOf("-") + 2, str
						.indexOf(";"));
				id2 = id2.replaceAll(" ", "");
				//System.out.println(id1 + "--" + id2);
				Vertex tmp1 = getVertNum(id1, list);
				Vertex tmp2 = getVertNum(id2, list);
				graph.addEdge(tmp1, tmp2);
			} else if (str.contains(";")) {
				String id = str.substring(0, str.indexOf(";"));
				id = id.replaceAll(" ", "");
				//System.out.println(id);
				Vertex tmp = new Vertex(id);
				list.add(tmp);
				graph.addVertex(tmp);
			}
		}
		in.close();
		return graph;

	}

	private Vertex getVertNum(String id, List<Vertex> list) {
		for (Vertex vertex : list) {
			if (vertex.getName().equals(id)) {
				return vertex;
			}
		}
		return null;
	}
}
